using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Data;
using System.Data.SqlClient;
using System.Data.Odbc;
using System.IO;
using System.Text.RegularExpressions;
using MyAlbum.Services;

namespace PersonalAlbum.Controllers
{
    public class SetupController : Controller
    {
        private IConfiguration _config;
        public SetupController()
        {
            _config = ObjectFactory.GetInstance<IConfiguration>();
        }
        public SetupController(IConfiguration config)
        {
            this._config = config;
        }
        //
        // GET: /Setup/

        public ActionResult Index()
        {
            if (this._config.FirstInstall)
            {
                List<SelectListItem> items = new List<SelectListItem>();
                foreach (var item in Enum.GetNames(typeof(DatabaseType)))
                {
                    items.Add(new SelectListItem() { Text = item, Value = item });
                }
                return View(items);
            }
            else
            {
                return new TextResult("This page can be viewed only on first installation. To show enable this page again, please change the parameter \"first install\"  to \"true\", on the file \\App_Data\\SiteConfig.xml");
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        //[ValidateAn tiForgeryToken()]
        public JsonResult CreateDatabase(DatabaseType dbType, string connectionString, bool deleteExisting)
        {
            try
            {
                IDbConnection con;
                switch (dbType)
                {

                    case DatabaseType.Sql:
                        try
                        {
                            con = new SqlConnection(connectionString);
                        }
                        catch (ArgumentException ae)
                        {
                            if (ae.Message.Contains("Format of the initialization string"))
                            {
                                return Utils.JavascriptError("The connection string is invalid. Message: " + ae.Message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                        break;
                    case DatabaseType.Access:
                        con = new OdbcConnection(connectionString);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("dbType", "Unknown database type: " + dbType);

                }
                string path = Server.MapPath("~/App_Data/Sql.txt");
                if (!System.IO.File.Exists(path))
                {
                    return Utils.JavascriptError("The file " + path + " is missing, please add it");
                }
                try
                {
                    con.Open();
                    con.Close();
                }
                catch (Exception e1)
                {
                    return Utils.JavascriptError("The connection string seams to be invalid, we could not connect. Reason: " + e1.Message);
                }
                string sql = System.IO.File.ReadAllText(path);
                using (con)
                {
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "select top 1 * from entry";
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();
                        }
                        try
                        {
                            object o = cmd.ExecuteScalar();
                            if (!deleteExisting)
                            {
                                //the tables exists, we need confirmation for deleting
                                return Json(new { confirm = "true" });
                            }
                            else
                            {
                                string pathDrop = Server.MapPath("~/App_Data/SqlDrop.txt");
                                if (!System.IO.File.Exists(pathDrop))
                                {
                                    return Utils.JavascriptError("The file " + pathDrop + " is missing, please add it");
                                }
                                string dropCommand = System.IO.File.ReadAllText(pathDrop).Replace("GO", ";");
                                using (var cmd2 = con.CreateCommand())
                                {
                                    if (con.State != ConnectionState.Open)
                                    {
                                        con.Open();
                                    }
                                    cmd2.CommandText = dropCommand;
                                    cmd2.ExecuteNonQuery();
                                }
                            }
                        }
                        catch
                        {
                        }
                        con.Close();
                    }
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = sql.Replace("GO", ";")
;

                        cmd.CommandTimeout = 180;
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();
                        }
                        //Server server = new Server(new ServerConnection(conn));

                        //server.ConnectionContext.ExecuteNonQuery(script);
                        cmd.ExecuteNonQuery();
                        return Json(new { success = "true" });
                    }
                }
            }
            catch (Exception e1)
            {
                return Utils.JavascriptError("An error occurred: " + e1.Message);
            }
        }

    }
    public enum DatabaseType
    {
        Sql,
        MySql,
        Access
    }
}
